package com.huahang.fashionpress.util;

import com.huahang.fashionpress.enums.ExceptionEnum;
import com.huahang.fashionpress.exception.ResultException;
import com.huahang.fashionpress.mapper.ImgMapper;
import com.huahang.fashionpress.model.Img;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.StyledEditorKit;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 用来作为上传文件的工具类
 * @Author: 阿俊哥
 * @Date: 2019/8/25 9:58
 * @Version 1.0
 */
@Slf4j
public class FileUtils {

    /**
     * 上传文件列表
     *
     * @param productId
     * @param imgStatus
     * @param imgMapper
     * @param request
     * @param fileName 文件上传表单的名称
     */
    public static void uploadFileList(String productId, int imgStatus, ImgMapper imgMapper,String fileName, HttpServletRequest request) {
        List<MultipartFile> fileList = ((MultipartHttpServletRequest) request).getFiles(fileName);
        for (MultipartFile file : fileList) {
            uploadFile(file, productId, imgStatus, imgMapper);

        }
    }

    /**
     * 添加一个文件
     *
     * @param file      文件
     * @param productId 商品id
     * @param imgStatus 图片属性状态
     * @param imgMapper 图片保存接口
     * @return
     */
    public static void uploadFile(MultipartFile file, String productId, int imgStatus, ImgMapper imgMapper) {

        if (file.isEmpty()) {
            log.info("未上传文件");
            throw new ResultException(ExceptionEnum.FILE_TO_ERROR);
        }
        //文件名
        String filename = file.getName();
        //文件保存的路径 保存在根目录下
        String path = "D:/华航达内实训/实训/fashionpress/src/main/resources/static/admin/jpg/";
        log.info("【文件上传】文件根目录：" + path);
        //获取文件的类型
        String originalFilename = file.getOriginalFilename();
        //要保存的文件的地址
        String imgName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        File dest = new File(path + imgName);

        //保存img
        Img img = new Img();
        img.setImgName(imgName);
        img.setProductId(productId);
        img.setImgStatus(imgStatus);
        try {
            file.transferTo(dest);
            imgMapper.insert(img);
            log.info("【文件上传】文件上传成功 文件上传的位置是" + dest.getAbsolutePath());
        } catch (IOException e) {
            log.info("【文件上传】文件保存失败，请重新上传 错误是：" + e);
            throw new ResultException(ExceptionEnum.FILE_TO_SAVE_ERROR);
        }
    }
}
